package cn.slipi.admin.common.handler.exception;

import cn.slipi.admin.common.exception.base.BizException;
import cn.slipi.admin.common.exception.base.ErrorMessage;
import cn.slipi.admin.common.response.builder.ResponseBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 服务层异常
 * 处理 BaseException 的子类异常
 *
 * @author lee
 */
@Component
public class ServiceExceptionHandler implements HandlerExceptionResolver {

    private static final Logger LOG = LoggerFactory.getLogger(ServiceExceptionHandler.class);

    @Autowired
    private MessageSource messageSource;

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        if (ex instanceof BizException) {
            BizException bizException = (BizException) ex;
            response.setStatus(200);
            try {
                bizException.setMsg(messageSource.getMessage(((BizException) ex).getMsg(), new Object[]{}, LocaleContextHolder.getLocale()));
            } catch (Exception e) {
                LOG.error(e.getMessage());
            }
            return ResponseBuilder.build(new ErrorMessage(bizException));
        }
        return null;
    }
}
